package com.qxzn.app.page.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qxzn.app.page.R;
import com.qxzn.app.util.AppUtil;

public class VerificationCodeView extends RelativeLayout {

    private Context context;
    private String code;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    private int length;
    private int codeNum = 6;//验证码位数
    private float textSize = 20;//验证码字体大小
    private int textColorSelected = Color.parseColor("#2A8CFF");//验证码字体选中颜色
    private int textColorNormal = Color.parseColor("#333333");//验证码字体正常颜色
    private int viewColorFill = Color.TRANSPARENT;//验证码下划线控件填充颜色
    private int viewColorSelected = Color.parseColor("#2A8CFF");//验证码下划线控件选中颜色
    private int viewColorNormal = Color.parseColor("#A6A6A6");//验证码下划线控件正常颜色
    private float viewBorderWidth = 2;//验证码边框宽度
    private float viewRadius = 10;//验证码边框圆角
    private int viewShape = 1;//验证码边框形状：1下划线；2方形边框
    private LinearLayout textLayout;
    private LinearLayout underLineViewLayout;
    private InputCompleteListener completeListener;
    private EditText editText;

    public VerificationCodeView(Context context) {
        this(context, null);
    }

    public VerificationCodeView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public VerificationCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initParams(context, attrs);
        addEditText();
        addViewLinearLayout();
        addTextLinearLayout();
    }

    private void initParams(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VerificationCodeView);
        codeNum = typedArray.getInt(R.styleable.VerificationCodeView_code_num, codeNum);
        textColorSelected = typedArray.getColor(R.styleable.VerificationCodeView_text_color_selected, textColorSelected);
        textColorNormal = typedArray.getColor(R.styleable.VerificationCodeView_text_color_normal, textColorNormal);
        viewColorFill = typedArray.getColor(R.styleable.VerificationCodeView_view_color_fill, viewColorFill);
        viewColorSelected = typedArray.getColor(R.styleable.VerificationCodeView_view_color_selected, viewColorSelected);
        viewColorNormal = typedArray.getColor(R.styleable.VerificationCodeView_view_color_normal, viewColorNormal);
        textSize = typedArray.getDimension(R.styleable.VerificationCodeView_text_size, textSize);
        viewShape = typedArray.getInt(R.styleable.VerificationCodeView_view_shape, viewShape);
        viewBorderWidth = typedArray.getDimension(R.styleable.VerificationCodeView_view_border_width, viewBorderWidth);
        viewRadius = typedArray.getDimension(R.styleable.VerificationCodeView_view_radius, viewRadius);
        if (typedArray != null) {
            typedArray.recycle();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (viewShape == 2) {
            for (int i = 0; i < codeNum; i++) {
                ViewGroup.LayoutParams params = underLineViewLayout.getChildAt(i).getLayoutParams();
                params.width = (w - dip2px(6) * codeNum) / codeNum;
                params.height = params.width - dip2px(6);
                underLineViewLayout.getChildAt(i).setLayoutParams(params);
                textLayout.getChildAt(i).setLayoutParams(params);
            }
        }
    }

    private void addEditText() {
        editText = new EditText(context);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(50));
        params.addRule(CENTER_VERTICAL);
        editText.setLayoutParams(params);
        editText.setCursorVisible(false);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(codeNum)});
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setTextColor(Color.TRANSPARENT);
        editText.setBackground(null);
        addView(editText);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                AppUtil.showLog(s);
                code = s.toString();
                length = code.length();
                resetValue();
                setValue(code, length);
                if (length == codeNum && completeListener != null) {
                    completeListener.onInputComplete(code);
                }
            }
        });
    }

    private void addTextLinearLayout() {
        textLayout = new LinearLayout(context);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textLayout.setLayoutParams(params);
        textLayout.setId(R.id.et_code);
        textLayout.setOrientation(LinearLayout.HORIZONTAL);
        textLayout.setWeightSum(codeNum);
        addView(textLayout);

        for (int i = 0; i < codeNum; i++) {
            textLayout.addView(getTextView());
        }
    }

    private TextView getTextView() {
        TextView textView = new TextView(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
        params.leftMargin = dip2px(6);
        params.rightMargin = dip2px(6);
        textView.setLayoutParams(params);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(textColorNormal);
        textView.setTextSize(textSize);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        return textView;
    }

    private void addViewLinearLayout() {
        underLineViewLayout = new LinearLayout(context);
        if (viewShape == 1) {
            LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(BELOW, R.id.et_code);
            underLineViewLayout.setLayoutParams(params);
        }
        underLineViewLayout.setOrientation(LinearLayout.HORIZONTAL);
        underLineViewLayout.setWeightSum(codeNum);
        addView(underLineViewLayout);

        for (int i = 0; i < codeNum; i++) {
            underLineViewLayout.addView(getUnderLineView());
        }
        setViewSelectedBackground(underLineViewLayout.getChildAt(0));
    }

    private View getUnderLineView() {
        View view = new View(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, Math.round(viewBorderWidth), 1);
        params.leftMargin = dip2px(6);
        params.rightMargin = dip2px(6);
        view.setLayoutParams(params);

        setViewNormalBackground(view);
        return view;
    }

    private void setViewNormalBackground(View view) {
        if (viewShape == 1) {
            view.setBackgroundColor(viewColorNormal);
        } else if (viewShape == 2) {
            view.setBackground(getDrawable(viewColorNormal));
        }
    }

    private void setViewSelectedBackground(View view) {
        if (viewShape == 1) {
            view.setBackgroundColor(viewColorSelected);
        } else if (viewShape == 2) {
            view.setBackground(getDrawable(viewColorSelected));
        }
    }

    private Drawable getDrawable(int borderColor) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(viewColorFill);
        drawable.setCornerRadius(viewRadius);
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setStroke(Math.round(viewBorderWidth), borderColor);
        return drawable;
    }

    private void setValue(String code, int length) {
        if (length == 0) {
//            for (int i = 0; i < codeNum; i++) {
//                if (i == 0) {
            setViewSelectedBackground(underLineViewLayout.getChildAt(0));
//                } else {
//                    setViewNormalBackground(underLineViewLayout.getChildAt(i));
//                }
//            }
        } else {
            for (int i = 0; i < length; i++) {
//                if (i < length) {
                ((TextView) textLayout.getChildAt(i)).setText(code.substring(i, i + 1));
                ((TextView) textLayout.getChildAt(i)).setTextColor(textColorSelected);
                setViewSelectedBackground(underLineViewLayout.getChildAt(i));
//                } else {
//                    if (i == length) {
//                        setViewSelectedBackground(underLineViewLayout.getChildAt(i));
//                    } else {
//                        setViewNormalBackground(underLineViewLayout.getChildAt(i));
//                    }
//                }
            }
        }
    }

    public void resetValue() {
        for (int i = 0; i < codeNum; i++) {
            ((TextView) textLayout.getChildAt(i)).setText(null);
            setViewNormalBackground(underLineViewLayout.getChildAt(i));
        }
    }

    //	将dip或dp值转换为px值，保证尺寸大小不变
    private int dip2px(float dipValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public void setCodeNum(int codeNum) {
        this.codeNum = codeNum;
    }

    public int getCodeNum() {
        return codeNum;
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public void setCompleteListener(InputCompleteListener completeListener) {
        this.completeListener = completeListener;
    }

    public void clear() {
        resetValue();
        editText.setText(null);
    }

    public void setText(String text) {
        this.editText.setText(text);
        editText.setSelection(editText.getText().toString().length());
    }

    public String getText() {
        return this.editText.getText().toString().trim();
    }

    public EditText getEditText() {
        return editText;
    }

    public void enableSystemInput(boolean enable){
        editText.setFocusable(enable);
        editText.setFocusableInTouchMode(enable);
        editText.setClickable(enable);
    }

    public void setViewShape(int viewShape) {
        this.viewShape = viewShape;
    }

    public void setTextColorSelected(int textColorSelected) {
        this.textColorSelected = textColorSelected;
    }

    public void setTextColorNormal(int textColorNormal) {
        this.textColorNormal = textColorNormal;
    }

    public void setViewColorSelected(int viewColorSelected) {
        this.viewColorSelected = viewColorSelected;
    }

    public void setViewColorNormal(int viewColorNormal) {
        this.viewColorNormal = viewColorNormal;
    }

    public void setViewBorderWidth(float viewBorderWidth) {
        this.viewBorderWidth = viewBorderWidth;
    }

    public interface InputCompleteListener {
        void onInputComplete(String code);

    }
}
